import os
import yaml

from utils.log_util import logger


class YamlUtil:
    def __init__(self):
        # 测试数据目录
        self.yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "data/")

    def read_testcase_yaml(self, yaml_file_name: str, key_name=None):
        """
        读取 ../data/XX.yaml 测试数据
        :param yaml_file_name: yaml文件全名，str
        :param key_name: yaml文件内容的key，str
        :return: 返回yaml数据
        """
        try:
            with open(self.yaml_path + yaml_file_name, mode='r', encoding='utf8') as f:
                value = yaml.safe_load(f)
                if key_name:
                    return value[key_name]
                return value
        except FileNotFoundError as e:
            logger.error(f"文件 {self.yaml_path + yaml_file_name} 不存在，错误信息: {e}")
        except yaml.YAMLError as e:
            logger.error(f"yaml文件解析出错，错误信息: {e}")

    def extract_case_data(self, yaml_file_name: str, key_name):
        """从yaml文件读取数据，组装适合 parametrize 的数据用于数据驱动"""
        case_data = self.read_testcase_yaml(yaml_file_name, key_name)[0]  # 拿到数组,通过下标取出
        new_case_data = []
        for value in case_data['case_info']:  # 遍历 case_info
            # 组装符合参数化的数据，结合 parametrize 用于数据驱动
            new_case_data.append({"request_info": case_data['request_info'], "case_info": value})
        return new_case_data

    def write_extra_yaml(self, data: dict):  # 只操作 extract.yaml 文件
        """写入数据到yaml中，data为字典"""
        with open(self.yaml_path + "extract.yaml", mode='a', encoding='utf8') as f:
            # 读取之前的yaml内容
            old_value = self.read_extract_yaml()
            if old_value:
                # 和新传入的数据做结合
                for key, value in data.items():
                    old_value[key] = value
                # 清空数据
                self.clear_extract_yaml()
                yaml.dump(data=old_value, stream=f, allow_unicode=True, sort_keys=False)
            else:
                yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False)

    def read_extract_yaml(self):  # 只操作 extract.yaml 文件
        """只读取data下面的extract.yaml"""
        with open(self.yaml_path + "extract.yaml", mode='r', encoding='utf8') as f:
            value = yaml.safe_load(f)
            return value

    def clear_extract_yaml(self):  # 只操作 extract.yaml 文件
        """清理extract.yaml"""
        with open(self.yaml_path + "extract.yaml", mode='w', encoding='utf8') as f:
            f.truncate()


YamlUtil = YamlUtil()

if __name__ == '__main__':
    # data = YamlUtil.read_testcase_yaml('wx_tag.yaml')
    # print(f'测试打印 data>>>{data},type>>>{type(data)}')
    # data_key = YamlUtil.read_testcase_yaml('wx_tag.yaml', 'wx_tag_update')
    # print(f'测试打印 data_key>>>{data_key},type>>>{type(data_key)}')

    data_key = YamlUtil.extract_case_data('wx_tag.yaml', 'wx_access_token')
    print(data_key)

"""
[{
        'request_info': {
            'case_title': 'wx_access_token',
            'case_description': '企业微信获取 access_token',
            'url': '/cgi-bin/gettoken',
            'method': 'GET',
            'headers': {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        },
        'case_info': {
            'params': {
                'corpid': 'ww56a5312cbc695bd3',
                'corpsecret': '-YbU-aXDH0Twug2ghuP8KDDIyyFAlhJQWEyyTp5PYp8'
            },
            'validate': [{
                    'eq': ['$.errcode', 0]
                }, {
                    'contains': ['$.access_token', 'm']
                }, {
                    'eq': ['$.expires_in', 7200]
                }
            ]
        }
    }, {
        'request_info': {
            'case_title': 'wx_access_token',
            'case_description': '企业微信获取 access_token',
            'url': '/cgi-bin/gettoken',
            'method': 'GET',
            'headers': {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        },
        'case_info': {
            'params': {
                'corpid': 'ww56a5312cbc695bd3',
                'corpsecret': '-YbU-aXDH0Twug2ghuP8KDDIyyFAlhJQWEyyTp5PYp8'
            },
            'validate': [{
                    'eq': ['$.errcode', 0]
                }
            ]
        }
    }
]
"""